package org.mics.lang.security;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

/**
 * 转码工具类
 * @author mics
 * @date 2020年6月10日
 * @version  1.0
 */
public class EncodeUtil {
	/**
	 * 默认编码
	 */
    private static final String DEFAULT_URL_ENCODING = "UTF-8";
	
    /**
     * 字节数组转十六进制字符串
     * @author mics
     * @date 2022-8-19
     * @version  1.0
     * @param bytes 需要编码的字节数组
     * @return 十六进制字符串
     */
    public static String encodeHex(byte[] bytes) {
        return Hex.encodeHexString(bytes);
    }

   /**
    * 十六进制字符串转byte数组
    * @author mics
    * @date 2022-8-19
    * @version  1.0
    * @param  conent 十六进制字符串 
    * @return 字节数组
    */
    public static byte[] decodeHex(String conent) {
        try {
            return Hex.decodeHex(conent.toCharArray());
        } catch (DecoderException e) {
            throw new SecurityException("16进制解码错误",e);
        }
    }

    /**
     * 字节数组转Base64编码字符串
     * @author mics
     * @date 2022-8-19
     * @version  1.0
     * @param bytes 字节数组
     * @return  base64编码的字符串
     */
    public static String encodeBase64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 字节数组转base64编码字符串(URL安全转码，检验了字节数组中安全去除了非法字符
     * 将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548)
     * @author mics
     * @date 2022-8-19
     * @version  1.0
     * @param bytes 字节数组
     * @return base64编码的字符串
     */
    public static String encodeUrlSafeBase64(byte[] bytes) {
        return Base64.encodeBase64URLSafeString(bytes);
    }

   /**
    *  Base64字符串解码成字符数组
    * @author mics
    * @date 2022-8-19
    * @version  1.0
    * @param content base64字符串 
    * @return  字符数组
    */
    public static byte[] decodeBase64(String content) {
        return Base64.decodeBase64(content);
    }


    /**
     * URL 编码, Encode默认为UTF-8.
     */
    public static String urlEncode(String part) {
        try {
            return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new SecurityException("编码错误！",e);
        }
    }

    /**
     * URL 解码, Encode默认为UTF-8.
     */
    public static String urlDecode(String part) {
        try {
            return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new SecurityException("解码错误",e);
        }
    }

  /*  public static void main(String[] args) {
        String resource = "abcd";
        String hexResource = encodeBase64(resource.getBytes(StandardCharsets.UTF_8));
        System.out.println(hexResource);
        String cResource = new String(decodeBase64(hexResource),StandardCharsets.UTF_8);
        System.out.println(cResource);
    }*/
}
